package com.yam.michael.hibernate.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xunjia.exception.XunjiaException;
import com.yam.michael.hibernate.dao.KeywordsDao;
import com.yam.michael.hibernate.pojo.Keywords;

public class KeywordsDaoImpl extends HibernateDaoSupport implements KeywordsDao,Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7779465791607129859L;
	//日志
	private static final Logger logger =Logger.getLogger(KeywordsDaoImpl.class);

	@Override
	/**
	 * @category 添加关键字广告
	 * @param keywordsAdvInfo
	 * @return 
	 */
	@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED, rollbackFor = { XunjiaException.class })
	public void addKeywords(Keywords keywords) throws XunjiaException {
	  try {
		this.getHibernateTemplate().saveOrUpdate(keywords);
	} catch (DataAccessException e) {
		logger.info(e.getMessage());
		throw new XunjiaException("增加关键字广告发生错误,增加失败!!!");
	}
	}
	/** 按广告活动ID获取该组关键字广告
	 * @category 
	 * @param aid 活动ID
	 */
	@Override
	public Keywords getKeywordsById(long aid) throws XunjiaException {	
		try {
			return 	(Keywords) this.getHibernateTemplate().get(Keywords.class, new Long(aid));
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("按广告活动ID获取广告发生错误,获取失败!!");
		}
	}

	@Override
	/**
	 * @category 修改用户关键字广告信息
	 * @param    Keywords
	 * @return  
	 */
	public void updateKeywords(Keywords keywords) throws XunjiaException {
		try {
			this.getHibernateTemplate().saveOrUpdate(keywords);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("更新关键字广告发生错误,更新失败!!");
		}
	}
	@Override
	/**
	 * @category 删除用户关键字广告
	 * @param   Keywords
	 * @return 
	 */
	public void deleteKeywords(Keywords keywords)
			throws XunjiaException {
		try {
			this.getHibernateTemplate().delete(keywords);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("删除关键字广告发生错误,删除失败!!");
		}
	}
	@SuppressWarnings("unchecked")
	@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED, rollbackFor = { XunjiaException.class })
	@Override
	/**
	 * @category 关键字模糊查询
	 * @param keywords 关键字
	 * @param size   返回的结果集大小
	 * @param type   关键字广告类型
	 * @return
	 * @throws XunjiaException
	 */
	public List<Keywords> searchKeywordsByLike(final String keywords,final int size,final String type)
			throws XunjiaException {
		try {
			return (List<Keywords>) this.getHibernateTemplate().execute(new HibernateCallback(){
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query q = session.createQuery("FROM  Keywords AS k  where  k.type=? AND k.keywords Like ? AND k.status=3 order by k.price desc");
					q.setString(0, type);
					q.setString(1,"%"+ keywords+"%");
					q.setMaxResults(size);
					return q.list();
				}});
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("查找关键字发生错误,查找失败!!!!");
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<String> getKeywordsByLike(final String keywords, final int size)
			throws XunjiaException {
		try {
			return (List<String>) this.getHibernateTemplate().execute(new HibernateCallback(){
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					//查询类似关键字
					Query q = session.createQuery("select distinct k.keywords from Keywords as k where k.keywords like ?");
					q.setString(0, "%"+keywords+"%");
					//设置返回记录条数
					q.setMaxResults(size);
					Iterator it = q.iterate();
					//list用于保存关键字
					List<String> list = new ArrayList<String>();
					while(it.hasNext())
					{
						//将关键字保存进list里
						list.add((String)it.next());
					}
					return list;
				}});
		} catch (Exception e) {
			logger.info(e.getMessage());
			throw new XunjiaException("获取关键字发生错误,获取失败!!!!");
		}
	}
	
}
